package net.asrsmid.sample.adventureanalyzer.service;

import java.io.StringWriter;
import java.util.Properties;

import net.asrsmid.connection.AsRsApplicationPool;
import net.asrsmid.invoker.AsOlapInvoker;
import net.asrsmid.invoker.as.Table;
import net.asrsmid.sample.adventureanalyzer.model.AnalysisContext;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;

public class AdventureAnalyzerAsService extends AdventureAnalyzerService {

	public AdventureAnalyzerAsService(AsRsApplicationPool pool) {
		super(pool);
	}

	public Table getReport(AnalysisContext ctx) {
		Table table = null;
		try {
			AsOlapInvoker invoker = new AsOlapInvoker(pool.getAsOlapConnection(AS_APP_ID));
			table = invoker.getTable(generateMdxQuery(ctx));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return table;
	}

	public String generateMdxQuery(AnalysisContext ctx) {
		String mdx = null;
		
		if ("TABLE_REPORT".equalsIgnoreCase(ctx.getReportType()))
			mdx = getTableReportMdxQuery(ctx);
		else if ("GRAPHIC_REPORT".equalsIgnoreCase(ctx.getReportType()))
			mdx = getGraphicReportMdxQuery(ctx);
		
		return mdx;
	}
	
	private String getTableReportMdxQuery(AnalysisContext ctx) {
		VelocityEngine engine = new VelocityEngine();
		Properties props = new Properties();
		props.put("resource.loader", "class");
		props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		engine.init(props);
		Template template = engine.getTemplate("tableReport.vm");
		Context context = new VelocityContext();
		
		context.put("CONTEXT", ctx);
		
		StringWriter writer = new StringWriter();
		template.merge(context, writer);
		return writer.toString();
	}
	
	private String getGraphicReportMdxQuery(AnalysisContext ctx) {
		return getTableReportMdxQuery(ctx);
	}
}